import TableUtils from '../../DBUtils/DBUtils'
import Logger from '../../utils/Logger';
Logger.getLogger('InnerTableSchemaUtils');

// 缓存
const tableSchemaMap = new Map();
// const formSchemaMap = new Map();
// const formMap = new Map();

const SchemaUtils = {
  getTableSchema(tableName, schema) {
    if (tableSchemaMap.has(tableName)) {
      return tableSchemaMap.get(tableName)
    }

    const toCache = {};
    const newCols = [];
    const fieldMap = new Map();
    schema.forEach((field) => {
      if (field.options) {
        field.$$optionMap = this.transformOptionMap(field.options, field.showType)
      }

      fieldMap.set(field.key, field);
      if (field.primary) {
        toCache.primaryKey = field.key;
      }

      if(field.showInTable === false) {
        return;
      }
      const col = {};
      col.key = field.key;
      col.dataIndex = field.key;
      col.title = field.title;
      col.width = field.width;
      col.sorter = field.sorter;
      newCols.push(col);
    })
    toCache.tableSchema = newCols;
    toCache.fieldMap = fieldMap;
    // 表头 和 页面字段
    const ignoreCache = TableUtils.shouldIgnoreSchemaCache(tableName);
    if (!ignoreCache) {
      tableSchemaMap.set(tableName, toCache);
    }

    return toCache;
  },
  transformOptionMap(options, showType) {
    const optionMap = {};
      // 对于级联选择要特殊处理下
      if (showType === 'cascader') {
        const browseOption = (item) => {  // dfs
          optionMap[item.value] = item.label;
          if (item.children) {
            item.children.forEach(browseOption);
          }
        };
        options.forEach(browseOption);
      } else {
        for (const option of options) {
          optionMap[option.key] = option.value;
        }
      }

      return optionMap;
  }
}

export default SchemaUtils;